import Icon from '@/components/Icon'
import useInitState from '@/hooks/useInitState'
import {
  getAllChannelsActionCreator,
  getUserChannelsActionCreator,
} from '@/store/actions/home'
import { RootAction } from '@/types/store'
import { Popup, Tabs } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import ArticleList from './ArticleList'
import Channels from './Channels'

import styles from './index.module.scss'

const Home = () => {
  const history = useHistory()
  // 获取用户频道
  const { userChannels, activeId } = useInitState(
    getUserChannelsActionCreator
  ).home
  // console.log(userChannels)

  const [visible, setVisible] = useState(false)
  const dispatch = useDispatch()

  // 获取所有频道
  useInitState(getAllChannelsActionCreator)

  // 一进入页面 拿userChannels第0项的id设置成activeId
  useEffect(() => {
    dispatch({
      type: 'home/set_active_id',
      payload: userChannels[0]?.id,
    } as RootAction)
  }, [dispatch, userChannels])

  return (
    <div className={styles.root}>
      {/* 频道 Tabs 列表 */}
      <Tabs
        activeKey={'' + activeId}
        className="tabs"
        activeLineMode="fixed"
        onChange={(key) => {
          // 切换面板时执行
          // console.log(key)
          // 获取key同步到仓库中的activeId
          dispatch({
            type: 'home/set_active_id',
            payload: +key,
          } as RootAction)
        }}
      >
        {userChannels.map((item) => (
          <Tabs.Tab title={item.name} key={item.id}>
            {/* 每个频道下的文章列表 */}
            <ArticleList channelId={item.id}></ArticleList>
          </Tabs.Tab>
        ))}
      </Tabs>

      <div className="tabs-opration">
        {/* 搜索功能 */}
        <Icon name="iconbtn_search" onClick={() => history.push('/search')} />
        {/* 频道设置 */}
        <Icon name="iconbtn_channel" onClick={() => setVisible(true)} />
      </div>

      {/* 频道操作面板弹层  */}
      <Popup
        visible={visible}
        position="left"
        bodyStyle={{ width: '100vw' }}
        destroyOnClose
      >
        <Channels onClose={() => setVisible(false)}></Channels>
      </Popup>
    </div>
  )
}

export default Home
